package com.heima.comment.serivce.impl;

import com.heima.comment.dto.CommentRayLikeDto;
import com.heima.comment.dto.CommentRepayDto;
import com.heima.comment.dto.CommentRepaySaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApCommentRepay;
import com.heima.comment.entity.ApCommentRepayLike;
import com.heima.comment.serivce.IApCommentRepayService;
import com.heima.comment.vo.ApCommentRepayVo;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.dto.UserThreadLocalUtil;
import com.heima.common.enums.AppHttpCodeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author : wuqiang
 * @since : 2022-10-17
 */
@Service
public class ApCommentRepayServiceImpl implements IApCommentRepayService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 保存回复评论
     *
     * @param dto dto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //获取当前登录用户
        User user = UserThreadLocalUtil.get();
        if (user == null || user.getUserId() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //组装数据
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setUserId(user.getUserId());
        apCommentRepay.setUserName(user.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        // apCommentRepay.setLikes();
        apCommentRepay.setCreatedTime(new Date());
        mongoTemplate.save(apCommentRepay);

        //评论表增加回复数量
        Query query = new Query(Criteria.where("_id").is(dto.getCommentId()));
        Update update = new Update();
        update.inc("repay", 1);
        mongoTemplate.updateFirst(query, update, ApComment.class);
        return ResponseResult.okResult();
    }

    /**
     * 评论列表查询
     *
     * @param dto dto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        String commentId = dto.getCommentId();
        Date minDate = dto.getMinDate();
        //根据评论id查询
        Criteria criteria = Criteria
                .where("commentId").is(commentId)
                //分页时间查询小于前端传递时间
                .and("createdTime").lte(minDate);
        Query query = new Query(criteria);
        //默认查询10条
        query.limit(10);
        //按照创建时间倒序排序
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
        //获取当前登录用户
        User user = UserThreadLocalUtil.get();
        if (user != null && user.getUserId() != 0) {
            ArrayList<ApCommentRepayVo> apCommentRepayVos = new ArrayList<>();
            //查询当前用户点赞的评论回复数据
            for (ApCommentRepay apCommentRepay : apCommentRepays) {
                ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
                BeanUtils.copyProperties(apCommentRepay, apCommentRepayVo);
                //查询redis中的当前用户点赞信息
                Boolean flag = redisTemplate.hasKey("ap_comment_repay:" + user.getUserId() + ":" + apCommentRepay.getId());
                apCommentRepayVo.setOperation(flag ? 0 : 1);
                apCommentRepayVos.add(apCommentRepayVo);
            }
            return ResponseResult.okResult(apCommentRepayVos);
        }
        //未登录  游客 查询所有点赞  以及评论
        return ResponseResult.okResult(apCommentRepays);
    }

    @Override
    public ResponseResult likeCommentRepay(CommentRayLikeDto dto) {
        //参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //获取当前登录用户
        //只有登录了才能对评论点赞
        User user = UserThreadLocalUtil.get();
        if (user == null || user.getUserId() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        String commentRepayId = dto.getCommentRepayId();
        Integer operation = dto.getOperation();
        //组装数据
        ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
        apCommentRepayLike.setUserId(user.getUserId());
        apCommentRepayLike.setCommentRepayId(commentRepayId);
        apCommentRepayLike.setOperation(operation);

        mongoTemplate.save(apCommentRepayLike);

        //对回复评论表likes字段进行修改
        Query query = new Query(Criteria.where("_id").is(commentRepayId));
        Update update = new Update();
        //点击评论的时候先往redis中插入一个标记
        if (operation == 0) {
            //点赞评论回复
            update.inc("likes", 1);
            redisTemplate.boundValueOps("ap_comment_repay:" + user.getUserId() + ":" + commentRepayId)
                    .set("");     //只做标记没有具体含义
        } else {
            //取消点赞评论回复
            update.inc("likes", -1);
            redisTemplate.delete("ap_comment_repay:" + user.getUserId() + ":" + commentRepayId);
        }
        mongoTemplate.updateFirst(query, update, ApCommentRepay.class);
        return ResponseResult.okResult();
    }
}
